/**
 * 提交订单地址控制器
 */
var ConfirmOrderAddressController = (function () {
    function ConfirmOrderAddressController(context, addressServices, addressAction) {
        var _this = this;
        this.addressServices = addressServices;
        this.addressServices.addressAction = addressAction;
        this._context = context;
        $(this._context).on('click', function (e) {
            e = e || window.event;
            var target = e.target, $_target = $(target);
            if ($_target.hasClass('add-new-address')) {
                _this.addressServices.openDialog($('#edit-cont'), '新增收货地址');
            }
            else if ($_target.hasClass('edit-address')) {
                addressAction.context = $_target.parents('.address-box');
                var attr = $_target.attr('data'), data = $.parseJSON(attr);
                _this.addressServices.openDialog($('#edit-cont'), '编辑收货地址', data);
            }
            else if ($_target.hasClass('del-address')) {
                addressAction.context = $_target.parents('.address-box');
                _this.addressServices.delAddress(parseInt($_target.closest('.address-box').attr('data-id')));
            }
            else if ($_target.hasClass('set-default')) {
                addressAction.context = $_target.parents('.address-box');
                _this.addressServices.setDefault(parseInt($_target.closest('.address-box').attr('data-id')));
            }
        });
    }
    
    
    ConfirmOrderAddressController.prototype = {
    	
    	//判断地址是否为空 为空的话 弹出输入框  输入地址
    	addressEmptyAlert : function(){
    		if($('li.address-box>.step-tag').length == 0){
    		   this.addressServices.openDialog($('#edit-cont'), '新增收货地址');  		    	  
    		}
    	}
    		
    }
    return ConfirmOrderAddressController;
})();


/**
 * 提交订单页面地址操作后DOM事件
 */
var ConfirmAddressEvent = (function () {
    function ConfirmAddressEvent() {
    }

    function setHiddenInputVal(){
        //地址id
        var receiverIdVal =$('li.address-box>.step-tag.default').parent().attr('data-id');
        $("input[name=receiverId]").val(receiverIdVal);

        //支付方式
        var payTypeVal =$('#payMethod>.step-tag.default').attr('data-val');
        $("input[name=payType]").val(payTypeVal);

        //配送方式
        var deliveryMethodVal =  $('#deliveryMethod>.step-tag.default').attr('data-id');
        $("input[name=deliveryMethodId]").val(deliveryMethodVal);
    }

    ConfirmAddressEvent.prototype.add = function (data) {

        var _this = this;

        $('li.address-box>.step-tag.default').removeClass('default');
        // $('li.address-box>.step-tag').parent().hide();
        this.hideOtherAddress();

        var html = $(template('address-item', data)).show();
        $('div.address-list>ul>li:first').before(html);

        this.showOrHideAddressDel();
        
        //是否显示更多按钮
        this.showHideMoreAddressBtn();

        //设置隐藏INPUT值
        this.setHiddenInputVal();

        //加载配送方式
        this.loadDeliveryMethodList();

        //地址选中事件
        $('li.address-box>.step-tag').click(function(){
            $('li.address-box>.step-tag').removeClass('default');
            $(this).addClass('default');

            //设置隐藏INPUT
            setHiddenInputVal();

            _this.loadDeliveryMethodList();
        });

    };

    ConfirmAddressEvent.prototype.del = function () {

        this.context.remove();

        //设置选中
        this.setAddressSeleted();

        this.showOrHideAddressDel();

        //是否显示更多按钮
        this.showHideMoreAddressBtn();
        //设置隐藏INPUT值
        this.setHiddenInputVal();
        //加载配送方式
        this.loadDeliveryMethodList();
    };

    ConfirmAddressEvent.prototype.setDefault = function () {
        var $_context = $(this.context), $_parent = $_context.parent(), $_oldDef = $_parent.children('.default');
        var btnname = $_oldDef.find('.step-tag span').attr('alias'),
            _sName = $_oldDef.find('.addr-name').text();
        $_oldDef.show().find('.step-tag span').html(btnname == '' ? _sName:btnname);
        $_oldDef.removeClass('default').show();
        $_oldDef.find('.op-btns').append('<a class="set-default">设为默认地址</a>');

        $_context.addClass('default');
        //$_parent.prepend($_context);
        $_context.find('.step-tag span').html('默认地址');
        $_context.find('.op-btns a.set-default').remove();

        //设置隐藏INPUT值
        this.setHiddenInputVal();

    };

    ConfirmAddressEvent.prototype.edit = function (data) {
    	var _sAlias = data.alias.length ? data.alias : data.name;
    	if ($(this.context).find('.step-tag').hasClass('default')) _sAlias = '默认地址';
        $(this.context).find('.step-tag>span').html(_sAlias).attr('alias',data.alias).end().find('.edit-address').attr('data', data.data).end().find('.addr-info').html(data.category + data.address).end().find('.addr-tel').html(data.phone).end().find('.addr-name').html(data.name);
    };


    /**
     *  收货地址数量多于一个，则显示更多地址按钮,否则隐藏
     */
    ConfirmAddressEvent.prototype.showHideMoreAddressBtn = function(){
        $('#more-address').parent()[$('li.address-box>.step-tag').length > 1 ? 'show' : 'hide']();
        this.openMoreBtnText();
        
    };

    ConfirmAddressEvent.prototype.moreAddressClick = function() {
        var _this = this;
        $('#more-address').click(function(){
            var _b = $(this).hasClass('close')
            $('li.address-box>.step-tag').not('.default').parent()[_b ? 'slideUp' : 'slideDown']('normal');
            // $(this).toggleClass('close');
            _this[ _b ? 'openMoreBtnText' : 'closeMoreBtnText']();
        })
    }

    ConfirmAddressEvent.prototype.openMoreBtnText = function() {
         $('#more-address').removeClass('close').text('更多地址');
    }
    ConfirmAddressEvent.prototype.closeMoreBtnText = function() {
        $('#more-address').addClass('close').text('收起地址');
    }

    ConfirmAddressEvent.prototype.hideOtherAddress = function() {
        if ($('#more-address').hasClass('close')) {
            $('#more-address').trigger('click');
        } else {
            $('li.address-box>.step-tag').not('.default').parent().hide(); 
        }
    }



    /**
     * 若没有选中项，则默认选中第一个收货地址
     */
    ConfirmAddressEvent.prototype.setAddressSeleted = function(){
        var context = $('li.address-box>.step-tag');
        if(context && !context.hasClass('default')){
            context.first().parent().show();
            context.first().addClass('default');
        }

        //设置隐藏INPUT值
        this.setHiddenInputVal();
    };

    //判断地址栏是否为空
    ConfirmAddressEvent.prototype.isEmpty = function() {
        return this.getAddressListLen() === 0;
    }

    //获取地址数量
    ConfirmAddressEvent.prototype.getAddressListLen = function() {
        return $('li.address-box').length;
    }
    //当前的地址是否只剩一个
    ConfirmAddressEvent.prototype.isOnlyOne = function() {
        return !this.isEmpty() && this.getAddressListLen() === 1;
    }
    //
    ConfirmAddressEvent.prototype.showOrHideAddressDel = function() {
        $('li.address-box .del-address')[this.isOnlyOne() ? 'hide': 'show']();
    }

    /**
     * 设置提交订单数据 (隐藏的Input值)
     */
    ConfirmAddressEvent.prototype.setHiddenInputVal = setHiddenInputVal;

    /**
     *
     * 显示或隐藏固定条
     * @param {[type]} '#F-b-btn').position( [description]
     * @param nBtTop 固定的提交按钮top
     * @param nWinH window's height
     */
    ConfirmAddressEvent.prototype.showBottomBtn = function() {
        if ($(window).height() + $(window).scrollTop() - 20 >= $('#F-b-btn').position().top) {
            $('#F-payAction').hide();
        }
        else {
            $('#F-payAction').show();
        }
    };

    /**
     * 加载配送方式
     */
    ConfirmAddressEvent.prototype.loadDeliveryMethodList = function() {

        setHiddenInputVal();

        var _this = this,  receiverId = $("input[name=receiverId]").val(),weight = $("input[name=weight]").val();

        var data = {receiverId:receiverId, weight:weight};

        if(receiverId != "undefined" && weight != "undefined"){
            ajax({
                url: base + "/getDeliveryMethods.jhtml",
                type: 'POST',
                data: data,
                cache: false,
                success: function(data){
                    if (!data.length) {
                        _this.addressOutOfRange();
                        //禁用提交按钮
                        _this.disabledConfrimBtn();
                    } else {
                        //启用提交按钮
                        _this.enableConfirmBtn();

                        var html = template('delivery-method', {list:data});
                        $('#deliveryMethod').html(html);
                        setHiddenInputVal();

                        //配送方式
                        $('#deliveryMethod>.step-tag').click(function(e){
                            $('#deliveryMethod>.step-tag.default').removeClass('default');
                            $(this).addClass('default');
                            //设置隐藏INPUT
                            setHiddenInputVal();
                            _this.showFee();
                        });

                        _this.showFee();
                    }

                    
                }
            });
        }
    };

    //地址超出范围不可送达
    ConfirmAddressEvent.prototype.addressOutOfRange = function () {
        //显示提示信息
        var _$message = $("<div class='tips'>您当前的地址范围不可送达!</div>")
        _$message.css({
            color: 'red'
        })
        $('#deliveryMethod').html(_$message);
    }

    //启用提交按钮
    ConfirmAddressEvent.prototype.enableConfirmBtn = function() {
        $('.pay-action>a.hp-button').removeClass('disabled');
    }

    //禁用提交按钮
    ConfirmAddressEvent.prototype.disabledConfrimBtn = function() {
        $('.pay-action>a.hp-button').addClass('disabled');
    }
    //是否启用提交按钮
    ConfirmAddressEvent.prototype.isEnableOfConfirmBtn = function() {
        return !$('.pay-action>a.hp-button').hasClass('disabled');
    }

    /**
     * 显示运费
     */
    ConfirmAddressEvent.prototype.showFee = function(){
       var fee = parseFloat($('#deliveryMethod>.step-tag.default').attr('data-fee'));
       if(isNaN(fee)){
       	fee=0;
       }
        $("#shipFee").html("￥"+fee.toFixed(2));
        $(".total-amount").html("￥" + (fee + parseFloat(total)).toFixed(2));
        $("#totalAmount").html("￥" + (fee + parseFloat(total)).toFixed(2));
    };
    /**
     * 弹出提示框
     */
    ConfirmAddressEvent.prototype.addressEmptyAlert = function(){
      if($('li.address-box>.step-tag').length == 0){
    	  
//          oDialog.alert("收货地址为空，请新增收货地址!","提示", true);
    	  
      }
    };
    return ConfirmAddressEvent;
})();

$(function () {

    /**
     * 提交订单页面地址修改下启用
     * @param {[type]}
     */
    if ($('#P_confirm').length) {

        var confirmAddressEvent = new ConfirmAddressEvent();
        var oAddress = new AddressModule.Address(oDialog);

        oAddress.cityUrl = base + '/resource/plug/citySelect/city.min.js';
        oAddress.addUrl = base + '/member/saveReceiver.jhtml';
        oAddress.saveUrl = base + '/member/saveReceiver.jhtml';
        oAddress.delUrl = base + '/member/deleteReceiver.jhtml';
        oAddress.setDefaultUrl = base + '/member/setDefaultReceiver.jhtml';
        var confirmController = new ConfirmOrderAddressController($('#P_confirm'), oAddress, confirmAddressEvent);
        //收货地址为空提示
        confirmController.addressEmptyAlert();
     
//        confirmAddressEvent.addressEmptyAlert();
        //设置选中项
        confirmAddressEvent.setAddressSeleted();
        //加载配送方式
        confirmAddressEvent.loadDeliveryMethodList();
        //是否显示更多按钮
        confirmAddressEvent.showHideMoreAddressBtn();

        confirmAddressEvent.moreAddressClick();

        //设置提交订单初始值数据（隐藏INPUT初始值）
        confirmAddressEvent.setHiddenInputVal();


        //初始化是否显示或隐藏固定条
        confirmAddressEvent.showBottomBtn();


        //是否显示或隐藏固定条
        $(window).scroll(function () {
            confirmAddressEvent.showBottomBtn();
        });
        //窗口大小变化是否显示或者隐藏固定条
        $(window).resize(function(){
            confirmAddressEvent.showBottomBtn();
        });


        //地址选中事件
        $('li.address-box>.step-tag').click(function(){
            $('li.address-box>.step-tag').removeClass('default');
            $(this).addClass('default');

            //设置隐藏INPUT
            confirmAddressEvent.setHiddenInputVal();

            confirmAddressEvent.loadDeliveryMethodList();
        });


        //支付方式
        $('#payMethod>.step-tag').click(function(){
            $('#payMethod>.step-tag.default').removeClass('default');
            $(this).addClass('default');

            //设置隐藏INPUT
            confirmAddressEvent.setHiddenInputVal();
        });

        //提交订单事件
        $("div.pay-action>a.hp-button").click(function(){

            if (!confirmAddressEvent.isEnableOfConfirmBtn()) return false;

            if(!$('li.address-box>.step-tag').hasClass('default')){
                oDialog.alert("请选择或新增收货地址", "提示", true);
                return;
            }
            if(!$('#payMethod>.step-tag').hasClass('default')){
                oDialog.alert("请选择支付方式", "提示", true);
                return;
            }
            if(!$('#deliveryMethod>.step-tag').hasClass('default')){
                oDialog.alert("请选择配送方式","提示", true);
                return;
            }
            //设置隐藏INPUT
            confirmAddressEvent.setHiddenInputVal();

            $("#createOrderForm").submit();
            
        });

        //显示运费
        confirmAddressEvent.showFee();
    }


});

